<template>
	<view class="root">
		<view class="item-container" v-if="loding" :class="hasComment?'item-container':'item-margin-contaner'">

			<text class="item-title">{{blog.title}}</text>
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-desc"></rich-text>
			<image :src="blog.picture" mode="widthFix" class="item-focus"></image>
			<image :src="blog.user.avatar" mode="widthFix" class="item-avatar"></image>
			<view class="icon-container">
				<text
					:class="goodIds.indexOf(blog.id)>=0?'iconfont icon-shoucang ic-red':'iconfont icon-shoucang ic-gray'"
					@click.stop="changeGood(blog.id)"> </text>
				<text class="icon-text">{{blog.good}}</text>
				<image src="/static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="/static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
			<text class="iconfont icon-xialacaidanjiantou icon-tag" @click.stop="drop(blog.id)"></text>
		</view>
		<!-- 评论列表区 -->
		<view v-if="hasComment" class="item-container">
			<!-- 根评论 -->
			<view v-for="(parent,index) in parents" :key="parent.id">
				<view class="cmt-container">
					<text class="cmt-author">{{parent.nickName}}</text>
					<text class="cmt-time">{{parent.createTime}}</text>
					<image :src="parent.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickReply(parent)"> {{parent.content}}</text>
				</view>
				<!-- 子评论列表 -->
				<view v-if="replies[index].length > 0" class="reply-container">
					<view v-for="(reply, idx) in replies[index]" :key="reply.idx" class="reply-item">

						<view class="reply-info">
							<text class="reply-author">{{reply.nickName}}</text>
							<text class="reply-to">@{{reply.toUser}}</text>
							<text class="reply-time">{{reply.createTime}}</text>
						</view>
						<text class="reply-content" @click="clickReply(reply)">
							{{reply.content}}
						</text>
					</view>
				</view>
				<view v-if="index < parents.length - 1" class="cmt-line"></view>
			</view>
		</view>
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click="goLogin"></image>
			<textarea auto-height :value="inputValue" :placeholder="inputHolder" @input="inputGetArea"
				class="input-area" />
			<text class="iconfont icon-comment-filling input-commit" @click="clickComment"></text>
		</view>
		<login-dialog ref="login" @login="afterLogin"></login-dialog>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodIds: [],
				blog: {

				},
				loding: false,
				parents: [],
				replies: [],
				hasComment: false,
				avatar: '../../static/icons/default_user.png',
				inputValue: '',
				inputHolder: '请输入评论内容...',
				parentId: null
			}
		},
		onLoad(options) {
			let ids = uni.getStorageSync(this.$params.key_good_ids)
			if (ids) {
				this.goodIds = ids
			}
			let id = options.id
			this.addReadCount(id)
			this.$noti.add(this.$params.noti_login_status, this.afterLogin(), this)
			// this.getBlog(id)
		},
		onUnload(){
			this.$noti.remove(this.$params.noti_login_status, this.afterLogin(), this)
		},
		methods: {
			clickReply(reply) {
				this.parentId = reply.id,
					this.inputHolder = '@' + reply.nickName
			},
			clickComment() {
				let app = getApp()
				if (app.globalData.token.length == 0) {
					this.$refs.login.show()
					return
				}
				if (this.inputValue.length == 0) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'fail'
					});
					return

				}
				let url = this.$params.host + this.$params.action_comment
				let data = {
					nick_name: app.globalData.nickName,
					avatar: '/' + app.globalData.avatar,
					email: app.globalData.email,
					content: this.inputValue,
					blog_id: this.blog.id,
					parent: this.parentId,
					token: app.globalData.token,
					is_owner: app.globalData.id == this.blog.user.id
				}
				uni.showLoading({
					title: '上传评论……',
					mask: false
				})
				this.$req.post(url, data, res => {
					// console.log(res)

					res = res.data
					let cmt = res.data
					let comments = this.blog.comments.concat(cmt)
					this.blog.comments = comments
					console.log(comments.length)
					this.formatComments(comments)
					this.hasComment = this.blog.comments.length > 0
					this.inputValue = ''
					this.parentId = null
					this.inputHolder = '请输入评论内容'
					this.$noti.post(this.$params.noti_refresh_comment, {
						blogId: this.blog.id,
						comment: cmt
					})
				}, () => {
					uni.hideLoading()
				})
			},
			inputGetArea(e) {
				// console.log(e)
				this.inputValue = e.detail.value
			},
			afterLogin() {
				this.avatar = this.$params.host + getApp().globalData.avatar
			},
			goLogin() {
				this.$refs.login.show()
			},
			//递归查找评论数据子孙
			findAllChildren(parent, comments) {
				let result = []
				comments.forEach(c => {
					if (parent.id == c.parentId) {
						c.toUser = parent.nickName
						result.push(c)
						result = [...result, ...this.findAllChildren(c, comments)]
					}
				})
				return result
			},

			//格式化评论数据
			formatComments(comments) {
				// console.log(comments)
				if (comments == 0) {
					return
				}

				let parents = []
				comments.forEach(c => {
					if (!c.avatar.startsWith('http')) {
						c.avatar = this.$params.host + c.avatar.substring(1)
					}
					c.createTime = this.$formatTime(new Date(c.createTime))
					if (c.parentId == null) {
						parents.push(c)
					}

				})
				// console.log(parents)
				parents.sort(function(p1, p2) {
					return new Date(p2.createTime).getTime() - new Date(p1.createTime).getTime()
				})


				// console.log(parents)
				let replies = new Array(parents.length).fill([])
				let index = 0
				parents.forEach(p => {
					let cmmts = []
					cmmts = [...cmmts, ...this.findAllChildren(p, comments)]
					replies[index++] = cmmts
				})
				// console.log(parents)
				// console.log(replies)

				this.parents = parents
				this.replies = replies
				this.hasComment = comments.length > 0
				// console.log(this.replies)

			},
			changeGood(id) {
				// console.log(id)
				let good = true
				if (this.goodIds.indexOf(id) >= 0) {
					good = false
				}
				if (good) {
					this.goodIds = [...this.goodIds, id]
				} else {
					let index = this.goodIds.indexOf(id)
					if (index >= 0) {
						this.goodIds[index] = this.goodIds[this.goodIds.length - 1]
						this.goodIds.pop()
					}
				}
				uni.setStorageSync(this.$params.key_good_ids, this.goodIds)
				this.postGood(id, good)

			},
			postGood(id, good) {
				uni.showLoading({
					title: '点赞……',
					mask: false
				})
				let url = this.$params.host
				let action = good ? this.$params.action_add_good : this.$params.action_del_good
				url += action

				let data = {
					"id": id
				}
				this.$req.postQuery(url, data, res => {
					this.blog.good = res.data.data
					this.$noti.post(this.$params.noti_refresh_good, {
						id: id,
						count: res.data.data
					})
				}, () => {
					uni.hideLoading()
				})

			},

			refreshPrevPage(id, count) {
				let pages = getCurrentPages()
				let prev = pages[pages.length - 2]
				prev.refreshReadCount(id, count)
			},
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_add_read
				let data = {
					"id": id
				}
				this.$req.postQuery(url, data, res => {
					// console.log(res)
					this.blog.readCount = res.data.data
					//第一种方式
					// this.refreshPrevPage(id, res.data.data)
					let count = res.data.data
					this.$noti.post(this.$params.noti_refresh_count, {
						id,
						count: res.data.data
					})

				}, () => {
					this.getBlog(id)
				})
			},
			getBlog(id) {
				let url = this.$params.host + this.$params.action_top_blogs + id
				this.$req.get(url, res => {
					// console.log(res)
					let blog = res.data.data
					// console.log(blog.user)
					uni.setNavigationBarTitle({
						title: blog.user.nickName
					})
					blog.picture = this.$params.host + blog.picture
					blog.user.avatar = this.$params.host + blog.user.avatar
					blog.creatTime = this.$formatTime(new Date(blog.creatTime))
					blog.updateTime = this.$formatTime(new Date(blog.updateTime))
					blog.content = blog.content.replace(/https/gi, 'http').replace(/\<img/gi,
						'<img class="rich-img" ')
					// console.log(blog)

					this.blog = blog
					this.formatComments(blog.comments)
					this.loding = true

				})
			}
		}
	}
</script>

<style>
	@import url("blog.css")
</style>